M=require("ming_node");
const rootPath="/root"
//完整line返回,不完整返回null

let curDir="";

function aline(line){
    if(line.startsWith(".")){
        oldLine=line
    }else {

    }
    return function(line){
        if(line.startsWith(".")){
            return null
        }else {
            if(line.startsWith("total")){
                return  oldLine+" "+line
            }else {
                return line;
            }
        }
    }
}

function parseDir(line){
    let arr= line.split(": total ");
    arr[0]=arr[0].replaceAll(":","")
    let n= M.getFileNameByUrl(arr[0]);
    let p=arr[0].replaceAll(".","");
    curDir=p;
    let d=p.substr(0,p.lastIndexOf("/"))
    if(d==""){
        d="/"
    }
    return {
        f:0,
        n,
        s:0,
        p,
        d:d
    }
}

function parseFile(line){
    let arr= line.split(/\s+/);
    //let n= M.getFileNameByUrl(arr[0]);

     let s=arr[4];
     let n="";
     for (let i=7;i<arr.length;i++){
          n=n+arr[i];
     }
    let p=curDir+"/"+n;
     let t=arr[5]+" "+arr[6];
    return {
        f:1,
        t,
        n,
        s,
        p,
        d:curDir
    }
}


function parseLine(r){
    sline=aline(r);
    curLine= sline(r);
   // console.log(curLine)
    if(curLine==null){
        return null;
    }else {
        return curLine;
    }
}


let rArr=[];

async function main(){
   await  M.readLine("tree.txt",line=>{
        let o=null
        line=parseLine(line);
        if (line==null){
            return
        }
        if(line.startsWith(".")){
            o=  parseDir(line);
        }
        if(line.startsWith("-")){
            o= parseFile(line);
        }
        if(o!=null){
            rArr.push(o)
        }
    });

   M.writeObjToFile("tree.json",rArr)
}

main()
